package io.github.idol.login

import android.Manifest
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.databinding.DataBindingUtil
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import com.tbruyelle.rxpermissions2.RxPermissions
import io.github.idol.utils.InjectorUtils
import io.github.idol.roomlist.RoomListActivity
import io.github.idol.R
import io.github.idol.databinding.ActivityLoginBinding

class LoginActivity : AppCompatActivity() {

    private lateinit var activityLoginBinding: ActivityLoginBinding
    private lateinit var loginViewModel: LoginViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)

        activityLoginBinding = DataBindingUtil.setContentView(this, R.layout.activity_login)
        loginViewModel = ViewModelProviders.of(this, InjectorUtils.provideLoginViewModelFactory(application)).get(LoginViewModel::class.java)
        with(activityLoginBinding) {
            viewModel = loginViewModel
            setLifecycleOwner(this@LoginActivity)
            btnLogin.setOnClickListener {
                this@LoginActivity.loginViewModel.login()
            }
        }

        loginViewModel.getNavigateToMain().observe(this, Observer {
            if (it == true) {
                RoomListActivity.startRoomListActivity(this)
            }
        })

        checkPermissions()
    }

    private fun checkPermissions() {
        val rxPermissions = RxPermissions(this)
        rxPermissions.request(Manifest.permission.READ_PHONE_STATE).subscribe {
            loginViewModel.start()
        }
    }
}
